
<template>
    <div class="app-container">

        <!-- 表格查询 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
          <!-- 店铺名称 -->
          <el-form-item label="平台商品名称" prop="platformProductName">
              <el-input
                  v-model="queryParams.platformProductName"
                  placeholder="请输入平台商品名称"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
          </el-form-item>
          <el-form-item label="平台商品编码" prop="platformProductCode">
              <el-input
                  v-model="queryParams.platformProductCode"
                  placeholder="请输入平台商品编码"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
          </el-form-item>
          <el-form-item label="平台规格信息" prop="platformProductInfo">
              <el-input
                  v-model="queryParams.platformProductInfo"
                  placeholder="请输入平台规格信息"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
          </el-form-item>
          
          <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
  
        <!-- 表头操作 -->
        <el-row :gutter="10"  class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <el-col :span="1.8">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleUpload"
                >导入</el-button>
            </el-col>
        </el-row>

        <!-- 表格数据 -->
        <vxe-table
          border
          stripe
          v-loading="loading" 
          ref="tableRef"
          size="small"
          header-align="center"
          :row-config="rowConfig"
          :column-config="columnConfig"
          @checkbox-change="checkboxChangeEvent"
          @checkbox-all="checkboxAll"
          :data="tableDataList"
        >
          <!-- <vxe-column type="checkbox" width="80" fixed="left" drag-sort /> -->
          <vxe-column type="seq" title="序号" width="60" fixed="left" align="center" />
          <vxe-column field="platformProductName" show-overflow="title" align="center" title="平台商品名称"  />
          <vxe-column field="platformProductCode" show-overflow="title" align="center" title="平台商品编码" />
          <vxe-column field="platformProductInfo" show-overflow="title" align="center" title="平台商品规格信息" />
          <vxe-column field="platformName" show-overflow="title" align="center" title="平台类型" />
          <vxe-column field="shopName" show-overflow="title" align="center" title="店铺名称" />
          <vxe-column field="pictureUrl" show-overflow="title" align="center" title="图片">
            <template #default="{ row }">
               <!-- 点击弹出大图 -->
              <img :src="row.pictureUrl" alt="" style="width: 50px; height: 50px;" v-if="row.pictureUrl"
                @click="handlePreview(row.pictureUrl)"
              />
            </template>
          </vxe-column>
          <vxe-column field="createTime"  show-overflow="title" align="center" title="创建时间" />
          <vxe-column width="180" align="center" title="操作" fixed="right">
              <template #default="{ row }">
                  <el-button
                      size="mini"
                      type="text"
                      @click="handleUpdate(row)"
                  >
                      修改
                  </el-button>
              </template>
          </vxe-column>
        </vxe-table>

        <!-- 分页 -->
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    

        <!-- 新增弹窗 -->
        <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="60%" append-to-body @close="cancel">
            <el-form ref="form" :model="form" :rules="rules" label-width="130px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="平台商品编码" prop="platformProductCode">
                            <el-input v-model="form.platformProductCode" placeholder="请输入平台商品编码" :disabled="form.id" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="平台商品名称" prop="platformProductName">
                            <el-input v-model="form.platformProductName" placeholder="请输入平台商品名称" />
                        </el-form-item>
                    </el-col>
                     <el-col :span="8">
                        <el-form-item label="平台类型" prop="platformId">
                            <el-select v-model="form.platformId" placeholder="请选择平台类型">
                                <el-option
                                    v-for="dict in platformList"
                                    :key="dict.id"
                                    :label="dict.platformName"
                                    :value="dict.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="平台商品规格信息" prop="platformProductInfo">
                            <el-input v-model="form.platformProductInfo" placeholder="请输入平台商品规格信息" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="店铺名称" prop="shopId">
                             <el-select v-model="form.shopId" placeholder="请选择所属店铺">
                                <el-option
                                    v-for="dict in shopList"
                                    :key="dict.userId"
                                    :label="dict.shopName"
                                    :value="dict.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="图片" prop="pictureUrl">
                          <!-- 上传图片upload,只允许上传一张,png或者jpg格式 -->
                           <el-upload
                              class="upload-demo"
                              :limit="1"
                              :auto-upload="false"
                              :on-change="handleChangeImg"
                              :on-exceed="handleExceed"
                              :on-remove="handleRemove"
                              accept=".png, .jpg, .jpeg"
                              list-type="picture-card"
                              :file-list="form.imgList"
                           >
                               <i class="el-icon-plus"></i>
                               <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过2MB</div>
                           </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">
                    {{  form.id ? '保 存' : '确 定' }}
                </el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
  
        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body @close="handleDialogClose">
            <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :disabled="upload.isUploading"
                :auto-upload="false"
                :on-change="handleUploadChange"
                :on-remove="handleUploadRemove"
                :on-exceed="handleUploadExceed"
                drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
                <el-button @click="closeUploadDialog">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 图片预览弹窗 -->
        <el-dialog :visible.sync="previewVisible" width="600px" append-to-body>
            <img :src="previewImage" alt="" style="width: 100%; height: 100%;">
        </el-dialog>


    </div>
  </template>
  
  <script>
  import { 
    addplatformProduct,
    listplatformProducts,
    delplatformProduct,
    editplatformProduct,
    getplatformProduct,
    importplatformProduct,
    uploadImage,
    getImportTemplate
  } from "@/api/mes/sales/platformProduct";

  import { listPlatforms } from "@/api/mes/sales/platform";
  import { listShopBasic } from "@/api/mes/sales/shopBasic";
  import { getToken } from "@/utils/auth";
  
  export default {
    name: 'MemberBasic',
    data() {
      return {
        title: '',
        open: false,
        loading: false,
        total: 0,
        form: {
          imgList: []
        },
        rules: {
            platformProductCode:[{ required: true, message: '请输入平台商品代码', trigger: 'blur' }],
            platformProductName:[{ required: true, message: '请输入平台商品名称', trigger: 'blur' }]
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        tableDataList: [],
        platformList: [],
        shopList: [],
        upload: {
          open: false,
          title: '',
          isUploading: false,
          updateSupport: 0,
          headers: { Authorization: 'Bearer ' + getToken() }
        },
        columnConfig: {
          drag: true,
          resizable: true,
          storage: true,
          sortConfig: {
            trigger: 'cell',
            remote: true
          },
          align: 'center',
          headerAlign: 'center'
        },
        rowConfig: {
          drag: true,
          keyField: 'id',
          isHover: true,
          isCurrent: true
        },
        ids: [],
        previewImage: '',
        previewVisible: false,
      }
    },
    created() {
      this.getList();
      this.getListPlatforms();
      this.getShopList();
    },
    methods: {
      // 点击图片预览
      handlePreview(url) {
        this.previewImage = url;
        this.previewVisible = true;
      },
      getShopList() {
        listShopBasic({pageNum: 1, pageSize: 9999, enabled: 1}).then(response => {
          this.shopList = response.rows;
        });
      },
      getListPlatforms() {
        listPlatforms({pageNum: 1, pageSize: 9999, enabled: 1}).then(response => {
          this.platformList = response.rows;
        });
      },
      handleChangeImg(file) {
        // 只保留最新上传的一个文件
        this.form.imgList = [file];
      },
      handleUpload() {
        this.upload.title = '导入平台商品';
        this.upload.open = true;
      },
      getList(){
        this.loading = true;
        listplatformProducts(this.queryParams).then(response => {
          this.tableDataList = response.rows;
          this.$nextTick(() => {
            this.$refs.tableRef.setCurrentRow(this.tableDataList[0]);
          })
          if(response.rows?.length>0){
            this.cellId = response.rows[0].id;
          }
          this.total = response.total;
          console.log(response);
        }).finally(() => {
          this.loading = false;
        })
      },
      handleAdd(){
        this.title = '新增';
        this.form = {
          imgList: []
        };
        this.open = true;
      },
      handleUpdate(row){
        this.title = '修改';
        
        // 根据是否有图片URL来初始化imgList，避免闪烁
        const imgList = row.pictureUrl ? [{
          name: '已上传图片',
          url: row.pictureUrl
        }] : [];
        
        // 复制row对象并正确初始化imgList
        this.form = { 
            ...row,
            imgList: imgList
        };
        
        this.open = true;
      },
      handleQuery(){
        this.queryParams.pageNum = 1;
        this.getList();
      },
      resetQuery(){
        this.resetForm("queryForm");
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          poCode: null,
          vendorNick: null,
          poStatusList: undefined,
          poCheckStatusList: undefined,
        },
        this.getList();
      },
      submitForm(){
        this.$refs["form"].validate(valid => {
          if (valid) {
            // 先检查是否有图片需要上传
            if (this.form.imgList && this.form.imgList.length > 0 && this.form.imgList[0].raw) {
              // 检查文件大小是否超过2MB
              if (this.form.imgList[0].raw.size > 2 * 1024 * 1024) {
                this.$modal.msgError("文件大小不能超过2MB");
                return;
              }
              
              // 创建FormData对象用于上传图片
              const formData = new FormData();
              formData.append('file', this.form.imgList[0].raw);
              
              // 先上传图片获取URL
              this.loading = true;
              uploadImage(formData).then(response => {
                // 获取上传后的图片URL
                this.form.pictureUrl = response.url;
                this.saveFormData();
              }).catch(error => {
                this.$modal.msgError("图片上传失败");
                this.loading = false;
              });
            } else {
              // 没有新图片上传，直接保存表单数据
              this.saveFormData();
            }
          }
        })
      },
      
      // 保存表单数据
      saveFormData() {
        const params = {
          ...this.form,
        }
        // 删除表单中的imgList，不需要传递给后端
        delete params.imgList;

        if (this.form.id) {
          editplatformProduct(params).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          });
        } else {
          addplatformProduct(params).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          });
        }
      },
      
      cancel(){
        this.open = false;
        this.form = {};
      },
      // 处理超出上传限制
      handleExceed() {
        this.$message.warning('只能上传一张图片，请先删除已有图片再上传');
      },
      // 处理图片移除
      handleRemove() {
        this.form.imgList = [];
        this.form.pictureUrl = '';
      },
      // 处理导入文件变更
      handleUploadChange(file) {
        // 限制文件类型和大小
        const isExcel = file.raw.type === 'application/vnd.ms-excel' || 
                        file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if (!isExcel) {
          this.$message.warning('请上传Excel文件(xls, xlsx格式)');
          this.$refs.upload.clearFiles();
          return false;
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$message.warning('文件大小不能超过5MB');
          this.$refs.upload.clearFiles();
          return false;
        }
      },
      // 处理上传文件超出限制
      handleUploadExceed() {
        this.$message.warning('只能上传一个文件，请先删除已有文件');
      },
      // 处理导入文件移除
      handleUploadRemove() {
        this.$refs.upload.clearFiles();
      },
      // 处理对话框关闭
      handleDialogClose() {
        this.$refs.upload.clearFiles();
        this.upload.isUploading = false;
      },
      // 点击取消按钮
      closeUploadDialog() {
        this.upload.open = false;
      },
      // 导入模板
      importTemplate() {
        // 实现导入模板下载逻辑
        // getImportTemplate().then(response => {
        //   if (response.code === 200) {
        //     this.$download.excel(response.data, "平台商品导入模板");
        //   } else {
        //     this.$message.warning('模板下载失败');
        //   }
        // }).catch(() => {
        //   this.$message.warning('模板下载失败');
        // });
        this.$message.warning('下载导入模板功能开发中');
      },
      // 提交文件表单
      submitFileForm() {
        const fileObj = this.$refs.upload.uploadFiles[0];
        if (!fileObj) {
          this.$modal.msgError("请选择要上传的文件");
          return;
        }
        
        this.upload.isUploading = true;
        // 创建表单数据
        const formData = new FormData();
        formData.append('file', fileObj.raw);
        
        // 调用导入平台商品接口
        importplatformProduct(formData)
          .then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess(response.msg || "导入成功");
              this.upload.open = false;
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "导入失败");
            }
          })
          .catch(() => {
            this.$modal.msgError("导入失败，请检查文件格式是否正确");
          })
          .finally(() => {
            this.upload.isUploading = false;
          });
      },
      checkboxChangeEvent(checked){
        this.ids = checked.records.map(item => item.id)
      },
      checkboxAll(checked){
        this.ids = checked.records.map(item => item.id)
      },
    }
  }
  </script>
  
  <style lang="scss" scoped>
    .el-select{
      width: 100%;
    }
  </style>